package com.sms.activity;

import java.util.ArrayList;

import com.sms.database.datastore;

import com.sms.model.SMS;




import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendcontactActivity extends Activity {
    /** Called when the activity is first created. */
   
    	 Button btnSendSMS;
	     EditText txtPhoneNo;
	     EditText txtMessage;
	    public StringBuilder sb = new StringBuilder();
	    private static final String DEBUG_TAG = null;
	   // private static final int ACTIVITY_SENT = 0;
	    public Context context=this;
		
	    Cursor cursor = null;
	    
	    String message;
		/** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	        //--------------------------------getting Phone contact-----------------------------
	        
	        
	        try {
	              Uri result=getIntent().getData();
	            Log.v(DEBUG_TAG, "Got a contact result: "
	                    + result.toString());

                sb=getcontactdeatils(result);
	        }
	        catch (Exception e) {
	            Log.e(DEBUG_TAG, "Failed to get  data", e);
	        }
	            EditText Entry = (EditText) findViewById(R.id.txtMessage);
	            Entry.setText(sb.toString());
	        //----------------------------------------------------------------------------------
	        //To get phone number
	        
	        ArrayList<String> phonelist=getphonelist();
	        
	        if(phonelist.isEmpty())
	        {
	        	
	        }
	        else
	        {
	        
	        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtPhoneNo);
	        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, phonelist);
	        textView.setAdapter(adapter);
	        }
	        
	        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
	        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
	        txtMessage = (EditText) findViewById(R.id.txtMessage);
	        btnSendSMS.setOnClickListener(new View.OnClickListener() 
	        {
	            public void onClick(View v) 
	            {                
	                String phoneNo = txtPhoneNo.getText().toString();
	                String[] p=phoneNo.split("---");
	                Toast.makeText(getBaseContext(), 
	                        p[0], 
	                        Toast.LENGTH_SHORT).show();
	                 message = txtMessage.getText().toString();                 
	                if (phoneNo.length()>0 && message.length()>0)                
	                    sendSMS(p[0].toString(), message);                
	                else
	                    Toast.makeText(getBaseContext(), 
	                        "Please enter both phone number and message.", 
	                        Toast.LENGTH_SHORT).show();
	            }
	        });   
	    }
	    
	    
	    // Create the menu based on the XML defintion
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {

	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.layout.menu, menu);
	        return true;
	    }
	 // Reaction to the menu selection
	    @Override
	    public boolean onMenuItemSelected(int featureId, MenuItem item) {

	        switch (item.getItemId()) {
	        case R.id.sentmsg:
	            sentsms();
	            return true;
	        case R.id.fb:
	            sendemail();
	            return true;
	        }
	        return super.onMenuItemSelected(featureId, item);
	    }

	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {

	        switch (item.getItemId()) {
	        case R.id.sentmsg:
	            sentsms();
	               
	            return true; 	
	        	
	        }
	        return super.onOptionsItemSelected(item);
	    }
	    private void sentsms() {

	        Intent i = new Intent(SendcontactActivity.this, SentMessages.class);
	        startActivity(i);
	    }
	    private void sendemail() {
	    	
	    	 message = txtMessage.getText().toString(); 

        	Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

        	emailIntent.setType("text/plain");

        	//emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {email});

        	emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Contact Details");

        	emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);

        

        	startActivity(Intent.createChooser(emailIntent, "Send mail..."));

        	finish(); 
	        
	        //startActivity(i);
	    }
	    
	    
	    public ArrayList<String> getphonelist()
        {
        	Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,    null, null, null, null);
            
            ArrayList<String> phonelist = new ArrayList<String>();
            if (cur.getCount() > 0) {
            
            	while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String hasPhoneNumber = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
    		       if (Integer.parseInt(hasPhoneNumber) > 0) {
                      
                    
                     
                      
                     // Query the table
                     Cursor phoneCursor = getContentResolver().query(Phone.CONTENT_URI,
                             null, Phone.CONTACT_ID + "=?", new String[] { id },
                             null);
                     while(phoneCursor.moveToNext())
                     {
                    	 String phoneNumber = phoneCursor.getString(phoneCursor
                                 .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            phonelist.add(phoneNumber+"---"+name);       
                     }
    		       }
                }
            }
            return phonelist;
        }
	    
	    public StringBuilder getcontactdeatils(Uri result)
        {
        	StringBuilder sb=new StringBuilder();
        	
        	try
        	{
        		
        		
        		 cursor = managedQuery(result,null, null, null, null);
 	           
 	            if (cursor.moveToFirst()) {
 	            	String id1 = cursor.getString(
 	                        cursor.getColumnIndex(ContactsContract.Contacts._ID));
 	    	      String name = cursor.getString(
 	                        cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
 	    	      sb.append("Name : ");
 	    	       sb.append(name);
 	    	       sb.append("\n");
 	    	       String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
 	    	       if (Integer.parseInt(hasPhoneNumber) > 0) {
 	                     
 	                    
 	                    Uri myPhoneUri = Uri.withAppendedPath(
 	                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id1);
 	                     
 	                    
 	                    cursor = getContentResolver().query(Phone.CONTENT_URI,
 	                            null, Phone.CONTACT_ID + "=?", new String[] { id1 },
 	                            null);

 	                    int PhoneIdx = cursor.getColumnIndex(Phone.DATA);
 	                  
 	                    // Get the phone numbers from the contact
 	                    if (cursor.moveToFirst()) {
 	                         
 	                        // Get a phone number
 	                        String phoneNumber =cursor.getString(PhoneIdx);
 	                        sb.append("PhoneNumber : ");
 	                        sb.append(phoneNumber);
 	                        sb.append("\n");
 	                        
 	                    }
 	                } else {
 	                	sb.append("This contact doesn't have a phone number");
 	                	
 	                }


 	                Log.v(DEBUG_TAG, "Got data: " + name);
 	            } else {
 	                Log.w(DEBUG_TAG, "No results");
 	            }
 	        } catch (Exception e) {
 	            Log.e(DEBUG_TAG, "Failed to get  data", e);
 	        } 
 	        finally {
 	            if (cursor != null) {
 	                cursor.close();
 	            }
        	
        	
        }
 	       return sb;
        }
    
    //Function to get Phone list
   
    
    
    
    
    //Function for sending SMS
            
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
           
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);  
    //to store details in database
        SMS s=new SMS();
        s.setMessage(message);
        s.setPhoneNumber(phoneNumber);
       // ContactManager sm=new ContactManager();
        //sm.Insert(s);
        datastore db=new datastore(context);
		db.openDB();
		db.Insert(s);
		db.close();
		sentsms();

    }
}